package com.ziyun.erp.modules.order.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.ziyun.erp.modules.order.vo.OrderRandomConfigVo;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.sys.entity.SysLogEntity;
import io.renren.modules.sys.service.SysLogService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ziyun.erp.modules.order.dao.OrderRandomConfigDao;
import com.ziyun.erp.modules.order.entity.OrderRandomConfigEntity;
import com.ziyun.erp.modules.order.service.OrderRandomConfigService;

import io.renren.modules.sys.entity.SysUserEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("orderRandomConfigService")
public class OrderRandomConfigServiceImpl extends ServiceImpl<OrderRandomConfigDao, OrderRandomConfigEntity> implements OrderRandomConfigService {

    @Autowired
    private OrderRandomConfigDao orderRandomConfigDao;

    @Autowired
    private SysLogService sysLogService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Page<OrderRandomConfigEntity> page = this.selectPage(
                new Query<OrderRandomConfigEntity>(params).getPage(),
                new EntityWrapper<OrderRandomConfigEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void deleteUpdateBatchByIds(Integer[] ids) {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        Map<String, Object> param = new HashMap<>();
        param.put("username", user.getUsername());
        orderRandomConfigDao.deleteUpdateBatchByIds(param, ids);
    }

    @Override
    public List<OrderRandomConfigEntity> randomConfigList(Map<String, Object> params) {
        if (StringUtil.isNull(params.get("randomType"))) {
            throw new RRException("查询参数不能为空！");
        }
        String randomType = params.get("randomType").toString();
        /**
         * 1.普通订单 万元以下优惠
         * 2.普通订单 万元以上优惠
         * 3.报价订单 万元以下优惠
         * 4.报价订单 万元以上优惠
         */
        List<OrderRandomConfigEntity> list = this.baseMapper.selectList(new EntityWrapper<OrderRandomConfigEntity>()
                .eq("del", 0)
                .addFilterIfNeed(randomType.equals("1"), " random_condition = 1 and  random_type = 'normal'", "")
                .addFilterIfNeed(randomType.equals("2"), " random_condition = 0 and  random_type = 'normal'", "")
                .addFilterIfNeed(randomType.equals("3"), " random_condition = 1 and  random_type = 'quote'", "")
                .addFilterIfNeed(randomType.equals("4"), " random_condition = 0 and  random_type = 'quote'", "")
                .orderBy("min_order_amount")
        );
        return list;
    }

    @Override
    @Transactional
    public void batchUpdate(OrderRandomConfigVo orderRandomConfigVo) {
        // 1.将更新人 更新日期 赋值
        List<OrderRandomConfigEntity> orderRandomConfigList = orderRandomConfigVo.getOrderRandomConfigList();
        for (OrderRandomConfigEntity orderRandomConfig : orderRandomConfigList) {
            orderRandomConfig.setUpdateName(orderRandomConfigVo.getUpdateName());
            orderRandomConfig.setUpdateTime(orderRandomConfigVo.getUpdateData());
            // todo 加数据校验 待定
        }
        // 批量更新
        this.updateBatchById(orderRandomConfigList);
        // 将上次数据 记录日志
        List<OrderRandomConfigEntity> orderRandomConfigBackUpList = orderRandomConfigVo.getOrderRandomConfigBackUpList();
        JsonArray jsonArray = new JsonArray();
        for (OrderRandomConfigEntity orderRandomConfigBackUp : orderRandomConfigBackUpList) {
            // 取出关键字 存入系统日志
            String randomType = null;
            if (orderRandomConfigBackUp.getRandomCondition().intValue() == 1 && orderRandomConfigBackUp.getRandomType().equals("normal")) {
                randomType = "1";
            }
            if (orderRandomConfigBackUp.getRandomCondition().intValue() == 0 && orderRandomConfigBackUp.getRandomType().equals("normal")) {
                randomType = "2";
            }
            if (orderRandomConfigBackUp.getRandomCondition().intValue() == 1 && orderRandomConfigBackUp.getRandomType().equals("quote")) {
                randomType = "3";
            }
            if (orderRandomConfigBackUp.getRandomCondition().intValue() == 0 && orderRandomConfigBackUp.getRandomType().equals("quote")) {
                randomType = "4";
            }
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("id", orderRandomConfigBackUp.getDiscountId());
            jsonObject.addProperty("randomType", randomType);
            jsonObject.addProperty("minOrderAmount", orderRandomConfigBackUp.getMinOrderAmount());
            jsonObject.addProperty("maxOrderAmount", orderRandomConfigBackUp.getMaxOrderAmount());
            jsonObject.addProperty("minRandom", orderRandomConfigBackUp.getMinRandom());
            jsonObject.addProperty("maxRandom", orderRandomConfigBackUp.getMaxRandom());
            jsonObject.addProperty("minRandomAmount", orderRandomConfigBackUp.getMinRandomAmount());
            jsonObject.addProperty("maxRandomAmount", orderRandomConfigBackUp.getMaxRandomAmount());
            jsonArray.add(jsonObject);

        }
        SysLogEntity sysLog = new SysLogEntity();
        sysLog.setUsername(orderRandomConfigVo.getUpdateName());
        sysLog.setOperation("批量更新随机立减配置");
        sysLog.setMethod("com.ziyun.erp.web.modules.order.controller.batchUpdate");
        sysLog.setParams(jsonArray.toString());
        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));
        sysLog.setTime(1L);
        sysLog.setCreateDate(new Date());
        sysLogService.insert(sysLog);

    }
}
